package com.game.centerserver.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.game.centerserver.pojo.result.DSTServerProcessView;
import com.game.centerserver.pojo.result.HttpStateCodeResult;
import com.game.centerserver.pojo.result.ServerStateView;
import com.game.centerserver.service.HttpClientService;
import com.game.centerserver.utils.BaseUtil;
import jakarta.annotation.Resource;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.invoke.VarHandle;
import java.util.Base64;
import java.util.List;

/**
 * (TUser)表服务实现类
 *
 * @author makejava
 * @since 2024-10-29 16:07:01
 */
@Service("HttpClientService")
public class HttpClientServiceImpl implements HttpClientService {
    @Resource
    private RestTemplate restTemplate;


    @Override
    public HttpStateCodeResult<List<DSTServerProcessView>> getServerStateList(String ip, Integer port) {
        String url = "http://" + ip + ":" + port + "/getServerStateList";

        ResponseEntity<List<DSTServerProcessView>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            List<DSTServerProcessView> result = response.getBody();
            return new HttpStateCodeResult<List<DSTServerProcessView>>(200, "调用成功", result);
        } else {
            return new HttpStateCodeResult<List<DSTServerProcessView>>(response.getStatusCode().value(), "调用失败");
        }

    }


    /**
     * 通过acrchiveId启动游戏服务
     * @param ip
     * @param port
     * @param archiveID 存档ID
     * @param shard     何种世界地图（地上、洞穴）
     * @return
     */
    @Override
    public HttpStateCodeResult<String> startServerByArchiveID(String ip, Integer port, 
        String archiveID, String shard) {
        String url = "http://" + ip + ":" + port + "/startServerByArchiveID?archiveID=" + archiveID + "&shard=" + shard;
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            String result = response.getBody();
            return new HttpStateCodeResult<String>(200, "调用成功");
        } else {
            return new HttpStateCodeResult<String>(response.getStatusCode().value(), "调用失败");
        }
    }


    @Override
    public HttpStateCodeResult<ServerStateView> getSystemState(String ip, Integer port) {
            String url = "http://" + ip + ":" + port + "/getSystemState";
            ResponseEntity<ServerStateView> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<>() {
                    }
            );
            if (response.getStatusCode() == HttpStatus.OK) {
                ServerStateView result = response.getBody();
                return new HttpStateCodeResult<>(200, "调用成功", result);
            }
            return null;
    }

    @Override
    public HttpStateCodeResult<byte[]> callBackServerByArchiveID(String ip, Integer port, String archiveID) {
        String url = "http://" + ip + ":" + port + "/callBackServerByArchiveID?archiveID=" + archiveID;
        // 发送 GET 请求获取文件流
        ResponseEntity<byte[]> response = restTemplate.exchange(
                url,                  // 请求的 URL
                HttpMethod.GET,      // 请求方法
                null,                 // 请求实体，传入 null 因为是 GET 请求，不需要 RequestBody
                byte[].class          // 响应体类型：byte[] 表示字节流
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            byte[] result = response.getBody();
            return new HttpStateCodeResult<byte[]>(200, "调用成功", result);
        }
        return null;
    }

    @Override
    public HttpStateCodeResult<String> shutdownServer(String ip, Integer port, String archiveID) {
        String url = "http://" + ip + ":" + port + "/shutdownServer?archiveID=" + archiveID;
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            String result = response.getBody();
            return new HttpStateCodeResult<String>(200, "调用成功");
        } else {
            return new HttpStateCodeResult<String>(response.getStatusCode().value(), "调用失败");
        }
    }

    @Override
    public HttpStateCodeResult<String> buildNewServer(String ip, Integer port, 
        Integer memry_limit, double cpu_limit, String archiveId,
        File file) 
    {
        String url = "http://" + ip + ":" + port + "/buildNewServer";
        String shard = "Master,Caves";

        url += "?archiveID=" + archiveId + "&shard=" + shard + 
            "&memery_limit=" + memry_limit + "&cpu_limit=" + String.valueOf(cpu_limit);

//        if (!BaseUtil.isValidArchive(file.getName())) {
//            return new HttpStateCodeResult<String>(811, "调用失败");
//        }

        List<String> res;
        try {
            res = BaseUtil.uploadFile(url, file);
            Integer responseCode = Integer.parseInt(res.get(0));
            String responseBody = res.get(1);
    
            if (responseCode == 200) {
                String result = responseBody;
                return new HttpStateCodeResult<String>(200, "调用成功", result);
            } else {
                return new HttpStateCodeResult<String>(responseCode, "调用失败, " + responseBody, responseBody);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new HttpStateCodeResult<String>(811, "调用失败");
        }
    }

    @Override
    public HttpStateCodeResult<String> shutdownAllServer(String ip, Integer port) {
        String url = "http://" + ip + ":" + port + "/shutdownAllServer";

        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            String result = response.getBody();
            return new HttpStateCodeResult<String>(200, "调用成功", result);
        } else {
            return new HttpStateCodeResult<String>(response.getStatusCode().value(), "调用失败");
        }
    }


    @Override
    public HttpStateCodeResult<String> ackCallBackServer(String ip, Integer port, String archiveID) {
        String url = "http://" + ip + ":" + port + "/ackCallBackServer" + "?archiveID=" + archiveID;

        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            String result = response.getBody();
            return new HttpStateCodeResult<String>(200, "调用成功", result);
        } else {
            return new HttpStateCodeResult<String>(response.getStatusCode().value(), "调用失败");
        }
    }


    @Override
    public HttpStateCodeResult<String> updateDST(String ip, Integer port) {
        String url = "http://" + ip + ":" + port + "/updateDst";

        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<>() {
                }
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            String result = response.getBody();
            return new HttpStateCodeResult<String>(200, "调用成功", result);
        } else {
            return new HttpStateCodeResult<String>(response.getStatusCode().value(), "调用失败");
        }
    }
}
